<template>

  <div class="host">

    <div class="host_search">
      <div class="components-input-demo-size">
        <span>
          主机类别：
          <a-select default-value="lucy" style="width: 120px" @change="handleChange">
            <a-select-option value="jack">
              Jack
            </a-select-option>
            <a-select-option value="lucy">
              Lucy
            </a-select-option>

          </a-select>
        </span>
        <span>
          主机别名：
          <a-input placeholder="default size"/>
        </span>
        <span>
          连接地址：
          <a-input placeholder="default size"/>
        </span>
        <span>
          <a-button type="primary" icon="undo">
            刷新
          </a-button>
        </span>

      </div>

    </div>
    <div class="host_add" style="margin-top: 20px;">
      <span>
        <a-button type="primary" icon="plus" @click="showModal">
          新建
        </a-button>

      </span>


      <span>
        <a-button type="primary" icon="underline" @click="showExcelModal">
          批量导入
        </a-button>

      </span>
      <span>
         <a-button type="primary" icon="download" @click="downloadExcel">
          导出主机列表
        </a-button>
      </span>

    </div>

    <div>

      <a-modal v-model="excel_model_visible" title="批量导入" @ok="handleExcelOk">
        <template slot="footer">
          <a-button key="back" @click="handleUploadExcelCancel">
            取消
          </a-button>
          <a-button
            type="primary"
            :disabled="excel_fileList.length === 0"
            :loading="excel_uploading"
            style="margin-top: 16px"
            @click="handleExcelUpload"
          >
            {{ excel_uploading ? 'Uploading' : 'Start Upload' }}
          </a-button>
        </template>

        <div>
          <a-alert type="info"
                   message="导入或输入的密码仅作首次验证使用，并不会存储密码。"
                   banner
                   closable
          />
          <br/>
          <a-form :form="upload_excel_form">

            <a-form-item
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol"
              label="模板下载"
              help="请下载使用该模板填充数据后导入"
            >
              <a href="../../static/file/主机导入模板.xlsx" download="主机导入模板.xlsx">主机导入模板.xlsx</a>
            </a-form-item>

            <a-form-item
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol"
              label="默认密码"
              help="如果Excel中密码为空则使用该密码"
            >
              <a-input
                v-model="default_password"
                placeholder="请输入默认主机密码"
              />
            </a-form-item>

            <a-form-item
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol"
              label="导入数据"
            >

              <div class="clearfix">
                <a-upload :file-list="excel_fileList" :remove="handleExcelRemove" :before-upload="beforeExcelUpload"
                          v-decorator="[
                    'host_excel',
                    { rules: [{ required: true, message: '请上传文件' }] },
                  ]">
                  <a-button>
                    <a-icon type="upload"/>
                    Select File
                  </a-button>
                </a-upload>

              </div>


            </a-form-item>


          </a-form>
        </div>


      </a-modal>
    </div>

    <div>

      <a-modal v-model="visible" title="新建主机" @ok="handleOk" width="800px">

        <a-form-model
          ref="ruleForm"
          :model="add_host_form.form"
          :rules="add_host_form.rules"
          :label-col="add_host_form.labelCol"
          :wrapper-col="add_host_form.wrapperCol"
        >

          <a-form-model-item label="选择主机类别" prop="category">
            <a-select v-model="add_host_form.form.category" placeholder="请选择类别">
              <a-select-option :value="host_category_value.id" v-for="(host_category_value,host_category_index) in host_category_data" :key="host_category_index">
                {{host_category_value.name}}
              </a-select-option>

            </a-select>
          </a-form-model-item>
          <a-form-model-item ref="hostname" label="输入主机名" prop="hostname">
            <a-input
              v-model="add_host_form.form.hostname"
              @blur="
          () => {
            $refs.hostname.onFieldBlur();
          }
        "
            />
          </a-form-model-item>

          <a-form-model-item ref="name" label="输入链接信息" prop="name">

            <a-row>
              <a-col :span="8">
                <a-input addon-before="用户名" v-model="add_host_form.form.username"/>
              </a-col>
              <a-col :span="8">
                <a-input addon-before="@" v-model="add_host_form.form.ip_addr"/>
              </a-col>
              <a-col :span="8">
                <a-input addon-before="端口号" v-model="add_host_form.form.port"/>
              </a-col>

            </a-row>

          </a-form-model-item>

          <a-form-model-item ref="password" label="输入连接密码" prop="password">
            <a-input
              v-model="add_host_form.form.password"
              @blur="
          () => {
            $refs.password.onFieldBlur();
          }
        "
            />
          </a-form-model-item>

          <a-form-model-item label="描述" prop="desc">
            <a-input v-model="add_host_form.form.desc" type="textarea"/>
          </a-form-model-item>

        </a-form-model>


      </a-modal>
    </div>

    <div class="host_table">
      <a-table :columns="columns" :data-source="host_data" rowKey="id">
        <a slot="action" slot-scope="text,scope" href="javascript:;">
          <a-button type="link" size="small">编辑 |</a-button>
          <a-button type="link" size="small">删除 |</a-button>
          <a-button type="link" size="small">
            <router-link :to="'/hippo/console/' + scope.id +'/'">console</router-link>
          </a-button>
        </a>

      </a-table>

    </div>


  </div>

</template>

<script>

const columns = [
  {title: 'id', dataIndex: 'id', key: 'id'},
  {title: '类别', dataIndex: 'category_name', key: 'category_name'},
  {title: '主机名称', dataIndex: 'hostname', key: 'hostname'},
  {title: '连接地址', dataIndex: 'ip_addr', key: 'ip_addr'},
  {title: '端口号', dataIndex: 'port', key: 'port'},
  {title: '描述', dataIndex: 'desc', key: 'desc'},
  {title: 'Action', dataIndex: '', key: 'x', scopedSlots: {customRender: 'action'}},
];

// const data = [
//   {
//     id: 1,
//     category_name: 'John Brown',
//     hostname: 3
//     ip_addr: 'New Yor2,k No. 1 Lake Park',
//     port: 'New York No. 1 Lake Park',
//     desc: 'New York No. 1 Lake Park',
//   },
//   {
//     id: 2,
//     name: 'Jim Green',
//     age: 42,
//     address: 'London No. 1 Lake Park',
//     description: 'My name is Jim Green, I am 42 years old, living in London No. 1 Lake Park.',
//   },
//   {
//     id: 3,
//     name: 'Joe Black',
//     age: 32,
//     address: 'Sidney No. 1 Lake Park',
//     description: 'My name is Joe Black, I am 32 years old, living in Sidney No. 1 Lake Park.',
//   },
// ];

const formItemLayout = {
  labelCol: {span: 8},
  wrapperCol: {span: 12},
};

export default {
  name: "Host",
  data() {
    return {
      // excel部分的数据属性
      formItemLayout,
      excel_fileList: [],  // 将选择的文件对象列表
      excel_uploading: false,

      upload_excel_form: this.$form.createForm(this, {name: 'coordinated'}),

      default_password: '', // 上传的Excel数据默认使用的密码

      // 模态对话框相关属性
      loading: false,

      confirmLoading: false,
      upload_excel_headers: {
        authorization: 'authorization-text',
      },

      host_data: [],
      host_category_data: [],  // 主机类别数据
      columns,
      visible: false,
      excel_model_visible: false, // 批量导入对话框的显示和隐藏控制

      add_host_form: {
        labelCol: {span: 4},
        wrapperCol: {span: 14},
        other: '',
        form: {
          hostname: '',
          category:'',
          username: '',
          ip_addr: '',
          port: 22,
          password: '',
          desc: '',
        },
        rules: {
          hostname: [
            {required: true, message: '请输入主机名称', trigger: 'blur'},
            {min: 1, max: 100, message: 'Length should be 1 to 100', trigger: 'blur'},
          ],
          username: [
            {required: true, message: '请输入主机名称', trigger: 'blur'},
            {min: 1, max: 100, message: 'Length should be 1 to 100', trigger: 'blur'},
          ],
          ip_addr: [
            {required: true, message: '请输入主机名称', trigger: 'blur'},
            {min: 1, max: 100, message: 'Length should be 1 to 100', trigger: 'blur'},
          ],
          port: [
            {required: true, message: '请输入主机名称', trigger: 'blur'},
            {min: 1, max: 100, message: 'Length should be 1 to 100', trigger: 'blur'},
          ],
          password: [
            {required: true, message: '请输入主机名称', trigger: 'blur'},
            {min: 1, max: 100, message: 'Length should be 1 to 100', trigger: 'blur'},
          ],


        },
      }

    }
  },
  created() {
    this.get_host_data();
    this.get_host_category_data();
  },

  methods: {
    // 下载主机文件
    downloadExcel(){
      let token = this.$settings.check_login(this);
      console.log(this);
      this.$axios.get(`${this.$settings.HOST}/host/host_excel`, {
        headers:{
          'Authorization': `jwt ${token}`
        }, responseType: 'blob',
      }).then((res) => {
        var blob = new Blob([res.data]);
        var url = window.URL.createObjectURL(blob);
        var aLink = document.createElement("a");
        aLink.href = url;
        aLink.setAttribute("download", "主机数据.xls")
        document.body.appendChild(aLink);
        aLink.click();
        document.body.removeChild(aLink); //下载完成后移除元素
        window.URL.revokeObjectURL(url); //释放blob对象
        this.$message.success("下载成功")
      }).catch((error) => {
        this.$message.error("下载失败")
      })
    },
    // 上传，批量导入
    handleExcelUpload(){
      // const { fileList } = this;
      const formData = new FormData();

      console.log('xxxxxxx',this.excel_fileList);
      // fileList.forEach(file => {
      //   formData.append('files[]', file);
      // });
      this.excel_fileList.forEach((file_value,file_index) => {
        formData.append('host_excel', file_value);
      });

      formData.append('default_password',this.default_password);

      let token = this.$settings.check_login(this);
      console.log('>>>>>',token);

      console.log(this);
      this.$axios.post(`${this.$settings.HOST}/host/host_excel/`,formData,{
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': `jwt ${token}`
        },
      }).then((res)=>{
        this.$message.success('上传成功')
        console.log(res.data);
        this.host_data = this.host_data.concat(res.data.data);
        this.excel_model_visible = false;
      }).catch((error)=>{

        this.$message.error('上传失败')
      })


      // this.uploading = true;

      // You can use any AJAX library you like
      // this.$axios.post(``)

      // reqwest({
      //   url: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
      //   method: 'post',
      //   processData: false,
      //   data: formData,
      //   success: () => {
      //     this.fileList = [];
      //     this.uploading = false;
      //     this.$message.success('upload successfully.');
      //   },
      //   error: () => {
      //     this.uploading = false;
      //     this.$message.error('upload failed.');
      //   },
      // });
    },

    // 取消上传按钮
    handleUploadExcelCancel() {
      this.excel_model_visible = false;
    },

    // 选中的想要上传的文件进行删除
    handleExcelRemove(file) {
      const index = this.excel_fileList.indexOf(file);
      const newFileList = this.excel_fileList.slice();
      newFileList.splice(index, 1);
      this.excel_fileList = newFileList;
    },
    // 上传之前将所有文件列表赋值给excel_fileList数据属性
    beforeExcelUpload(file) {
      // console.log('file>>>>>', file)
      this.excel_fileList = [...this.excel_fileList, file];
      // this.excel_fileList = this.excel_fileList.push(file);
      return false;
    },

    showExcelModal() {
      this.excel_model_visible = true;
    },
    handleExcelOk(e) {
      console.log(e);
      this.excel_model_visible = false;
    },


    showModal() {
      this.visible = true;
    },
    // 点击提交按钮进行数据的校验和保存, validate--校验
    handleOk(e) {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          // 前端校验成功之后做的事情
          // alert('submit!');
          // 发送请求携带主机数据到后台进行主机的添加
          // console.log('添加主机的数据>>>>',this.add_host_form.form)

          let token = sessionStorage.token || localStorage.token;
          console.log('>>>',token);

          this.$axios.post(`${this.$settings.HOST}/host/list/`, this.add_host_form.form,{

            headers: {
              'Authorization': `jwt ${token}`
            }

          }).then((res)=>{
            // this.host_category_data = res.data;
            this.host_data.push(res.data);
          }).catch((error)=>{
            this.$message.error('请求参数有误！！')
          })


        } else {
          console.log('error submit!!');
          return false;
        }
      });

      console.log(e);
      this.visible = false;
    },


    handleChange(value) {
      this.$refs.ruleForm.resetFields();
      console.log(`selected ${value}`);
    },

    // 获取主机类别数据
    get_host_category_data(){
      let token = sessionStorage.token || localStorage.token;

      this.$axios.get(`${this.$settings.HOST}/host/categorys/`, {
        headers: {
          'Authorization': `jwt ${token}`
        }
      }).then((res)=>{
        this.host_category_data = res.data;
      })
    },


    // 获取主机数据
    get_host_data() {
      let token = sessionStorage.token || localStorage.token;

      this.$axios.get(`${this.$settings.HOST}/host/list/`, {
        headers: {
          'Authorization': `jwt ${token}`
        }
      }).then((res) => {
        console.log(res);
        this.host_data = res.data;

      }).catch((error) => {

      })

    },

  }

}
</script>

<style scoped>

.components-input-demo-size .ant-input {
  width: 200px;
  margin: 0 8px 8px 0;
}

</style>
